﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Authentication.JwtBearer
{
  public class JwtCookieExtractor
  {
    private readonly RequestDelegate Next;
    private readonly String CookieName;

    public JwtCookieExtractor(RequestDelegate next, String cookieName)
    {
      Next = next;
      CookieName = cookieName;
    }

    public async Task Invoke(HttpContext context)
    {
      var cookie = context.Request.Cookies[CookieName];

      if (cookie != null)
      {
        context.Request.Headers.Append("Authorization", "Bearer " + cookie);
      }

      // move to next item in the request pipline
      await Next.Invoke(context);
    }
  }
}